package cn.tedu.reflect;

import cn.tedu.annotation.Component;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 假设这是一个项目启动类,
 * 此类运行时，为此类所在包中的由这个@Component注解描述的类创建对象。
 */
public class MainApplication {
    static ConcurrentHashMap<String,Object> map=new ConcurrentHashMap<>();
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        //获取当前类所在的包
        Class<?> clazz=MainApplication.class;
        Package aPackage = clazz.getPackage();
        String packageName = aPackage.getName();
        String packageDir = packageName.replace(".", "/");
        System.out.println(packageDir);
        String classPath=clazz.getClassLoader().getResource(packageDir).getPath();
        System.out.println(classPath);
        File file = new File(classPath);//cn/tedu/reflect
        File[] files = file.listFiles(f -> f.isFile() && f.getName().endsWith(".class"));
        //Arrays.stream(files).forEach(item-> System.out.println(item.getName()));
        //找到当前类所在包中由@Component注解描述的类
        for(File f:files) {
            String fileName=f.getName();
            String prefix=fileName.substring(0,fileName.lastIndexOf("."));
            Class<?> cls=clazz.getClassLoader().loadClass(packageName + "." +prefix);
            if(cls.isAnnotationPresent(Component.class)) {
                //通过反射构建此类对象
                Object obj=ObjectFactory.newInstance(cls);
                //将对象存储到容器
                map.put(prefix,obj);
            }
        }
        Object point = map.get("Point");
        System.out.println("point="+point);
    }
}
